package org.boot.wxipad.common.util.http.apache;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.entity.UrlEncodedFormEntity;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.core5.http.HttpHost;
import org.apache.hc.core5.http.message.BasicNameValuePair;
import org.apache.hc.core5.net.URIAuthority;
import org.boot.wxipad.common.util.http.RequestHttp;
import org.boot.wxipad.common.util.http.SimpleFormRequestExecutor;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author liyuncong
 * @version 1.0
 * @file ApacheSimplePostRequestExecutor
 * @brief ApacheSimplePostRequestExecutor
 * @details ApacheSimplePostRequestExecutor
 * @date 2024-08-09
 *
 * Edit History
 * ----------------------------------------------------------------------------
 * DATE                     NAME               DESCRIPTION
 * 2024-08-09               liyuncong          Created
 */
public class ApacheSimpleFormRequestExecutor extends SimpleFormRequestExecutor<CloseableHttpClient, HttpHost> {
    private static final Gson defaultGson = new Gson();

    public ApacheSimpleFormRequestExecutor(RequestHttp requestHttp) {
        super(requestHttp);
    }

    /**
     * default contentType application/x-www-form-urlencoded
     */
    @Override
    public String execute(String uri, String formEntity) throws IOException {

        HttpPost httpPost = new HttpPost(uri);

        HttpHost httpProxy = requestHttp.getRequestHttpProxy();
        if (httpProxy != null) {
            httpPost.setAuthority(new URIAuthority(httpProxy));
        }

        if (formEntity != null) {
            Map<String, Object> jsonObject = defaultGson.fromJson(formEntity, new TypeToken<>() {
            });
            List<BasicNameValuePair> formParams = new ArrayList<>(jsonObject.size());
            jsonObject.forEach((k, v) -> {
                BasicNameValuePair pair = new BasicNameValuePair(k, String.valueOf(v));
                formParams.add(pair);
            });

            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formParams, StandardCharsets.UTF_8);
            httpPost.setEntity(urlEncodedFormEntity);
        }

        try {
            return requestHttp.getRequestHttpClient().execute(httpPost, Utf8ResponseHandler.INSTANCE);
        } finally {
            httpPost.reset();
        }
    }
}
